package com.note.chh.notebook;

import android.Manifest;
import android.location.Address;
import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CacheUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.note.chh.notebook.Interface.PerfectClickListener;
import com.note.chh.notebook.Model.WeatherModel;
import com.note.chh.notebook.UI.base.BaseActivity;
import com.note.chh.notebook.UI.enjoy.MusicActivity;
import com.note.chh.notebook.UI.enjoy.VideoActivity;
import com.note.chh.notebook.UI.enjoy.WeatherActivity;
import com.note.chh.notebook.UI.homeFragment.EnjoyFragment;
import com.note.chh.notebook.UI.homeFragment.NotesFragment;
import com.note.chh.notebook.UI.homeFragment.StrokeFragment;
import com.note.chh.notebook.Uitls.DialogUtils;
import com.note.chh.notebook.Uitls.LocationUtils;
import com.note.chh.notebook.Uitls.UserUtil;
import com.note.chh.notebook.Uitls.gson.GsonImpl;
import com.note.chh.notebook.Uitls.statusBar.StatusBarUtils;
import com.note.chh.notebook.Widget.NoScrollViewPager;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.yinglan.alphatabs.AlphaTabsIndicator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.note.chh.notebook.MyApplication.currentCity;

//MainActivity
public class MainActivity extends BaseActivity {


    @BindView(R.id.mViewPager)
    NoScrollViewPager mViewPger;
    @BindView(R.id.alphaIndicator)
    AlphaTabsIndicator alphaTabsIndicator;
    @BindView(R.id.topbar)
    QMUITopBar topbar;
    @BindView(R.id.nav_view)
    NavigationView navView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;

    private ImageView iv_avatar;
    private LinearLayout ll_nav_weather;
    private LinearLayout ll_nav_about;
    private LinearLayout ll_nav_login;
    private LinearLayout ll_nav_video;
    private LinearLayout ll_nav_music;
    private View view;
    private TextView tv_username,tv_areaName,tv_level,mText_versionName;

    private String locality = "";//所在地
    private LocationClient mLocationClient;
    @Override
    public void initView() {


        MainAdapter mainAdapter = new MainAdapter(getSupportFragmentManager());
        mViewPger.setAdapter(mainAdapter);
        mViewPger.addOnPageChangeListener(mainAdapter);
        mViewPger.setNoScroll(true);//是否滑动
        alphaTabsIndicator.setViewPager(mViewPger);

        //控制导航标题栏显示的数字和点
//        alphaTabsIndicator.getTabView(0).showNumber(6);
//        alphaTabsIndicator.getTabView(1).showNumber(888);
//        alphaTabsIndicator.getTabView(2).showNumber(88);
//        alphaTabsIndicator.getTabView(3).showPoint();
        initDrawerLayoutStatus();
        initNav();
        initLocation();
    }
    private void requestLocation() {
        LocationClientOption  option = new LocationClientOption();
//        option.setScanSpan(5000);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    private void initLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                StringBuilder  currentPosition =  new StringBuilder();
                currentPosition.append("维度：").append(bdLocation.getLatitude()).append("\n");
                currentPosition.append("经度：").append(bdLocation.getLongitude()).append("\n");
                currentPosition.append("国家：").append(bdLocation.getCountry()).append("\n");
                currentPosition.append("省：").append(bdLocation.getProvince()).append("\n");
                currentPosition.append("市：").append(bdLocation.getCity()).append("\n");
                currentPosition.append("区：").append(bdLocation.getDistrict()).append("\n");
                currentPosition.append("街道：").append(bdLocation.getStreet()).append("\n");
                currentPosition.append("定位方式：");
                locality = bdLocation.getDistrict();
                tv_areaName.setText(locality);
                currentCity = locality;//给全局变量赋值 application中
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getWeatherData(locality);
                    }
                }).start();
                Log.e("tag","当前的定位方式="+bdLocation.getLocType());
                if(bdLocation.getLocType() == BDLocation.TypeGpsLocation){
                    currentPosition.append("GPS");
                }else if(bdLocation.getLocType() == BDLocation.TypeNetWorkLocation){
                    currentPosition.append("网络");
                }
//                UserUtil.dLog("currentPosition="+currentPosition);
            }
        });
//        mLocationClient.start();
    }



    @Override
    public void initTopBar() {
        super.initTopBar();
        topbar.setBackgroundColor(getResources().getColor(R.color.app_color_blue));
        topbar.addLeftImageButton(R.mipmap.ic_title_bar_menu,R.id.top_bar_left_menu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        topbar.setTitle(getResources().getString(R.string.notes));
    }

    @Override
    public void initData() {
        requestPermission();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //
        LocationUtils.unregister();
    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_main;
    }
    /**
     * 初始化侧滑菜单
     */
    private void initNav() {

        view = navView.inflateHeaderView(R.layout.nav_header_main);
        iv_avatar = (ImageView) view.findViewById(R.id.iv_avatar);
        tv_username = (TextView) view.findViewById(R.id.tv_username);
        tv_areaName = (TextView) view.findViewById(R.id.tv_areaName);
        tv_level = (TextView) view.findViewById(R.id.tv_level);
        ll_nav_music = (LinearLayout) view.findViewById(R.id.ll_nav_music);
        ll_nav_weather = (LinearLayout) view.findViewById(R.id.ll_nav_weather);
        ll_nav_about = (LinearLayout) view.findViewById(R.id.ll_nav_about);
        ll_nav_login = (LinearLayout) view.findViewById(R.id.ll_nav_login);
        ll_nav_video = (LinearLayout) view.findViewById(R.id.ll_nav_video);
        mText_versionName = (TextView) view.findViewById(R.id.mText_versionName);


        mText_versionName.setText("V"+AppUtils.getAppVersionName());
//        iv_avatar.setImageResource(R.mipmap.ic_person_logo);
//        tv_username.setText("蔡华辉");
    }

    @Override
    public void initListener() {
        super.initListener();
        //侧滑点击事件
        if (view != null) {
            iv_avatar.setOnClickListener(listener);
            ll_nav_music.setOnClickListener(listener);
            ll_nav_weather.setOnClickListener(listener);
            ll_nav_about.setOnClickListener(listener);
            ll_nav_login.setOnClickListener(listener);
            ll_nav_video.setOnClickListener(listener);
        }
    }

    /**
     * 初始化侧滑菜单的状态栏
     */
    private void initDrawerLayoutStatus(){
        StatusBarUtils.setColorNoTranslucentForDrawerLayout(this, drawerLayout,
                getResources().getColor(R.color.app_color_blue));
    }

    /**
     * 自定义菜单点击事件
     */
    private PerfectClickListener listener = new PerfectClickListener() {
        @Override
        protected void onNoDoubleClick(final View v) {
            drawerLayout.closeDrawer(GravityCompat.START);
            drawerLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    switch (v.getId()) {
                        case R.id.iv_avatar:

                            break;
                        case R.id.ll_nav_music:// 音乐
                            startActivity(MusicActivity.class);
                            break;
                        case R.id.ll_nav_video://视频
                            startActivity(VideoActivity.class);
                            break;
                        case R.id.ll_nav_weather://天气
                            startActivity(WeatherActivity.class);
                            break;
                        case R.id.ll_nav_about:// 关于

                            break;
                        case R.id.ll_nav_login:// 个人

                            break;
                        default:
                            break;
                    }
                }
            }, 0);
        }
    };
    //权限申请
    private void requestPermission(){
        PermissionUtils.permission(Manifest.permission.WRITE_EXTERNAL_STORAGE,//储存卡读写权限
                Manifest.permission.ACCESS_COARSE_LOCATION,//定位权限
                Manifest.permission.READ_CALENDAR,//系统日历读权限
                Manifest.permission.WRITE_CALENDAR)//系统日历写权限
                .rationale(new PermissionUtils.OnRationaleListener(){
                    @Override
                    public void rationale(final ShouldRequest shouldRequest){//设置拒绝权限后再次请求的回调接口
                        DialogUtils.cancelSureDialog(MainActivity.this,"权限申请","是否重新申请权限?")
                                .addAction("取消", new QMUIDialogAction.ActionListener() {
                                    @Override
                                    public void onClick(QMUIDialog dialog, int index) {
                                        shouldRequest.again(false);dialog.dismiss();
                                    }
                                })
                                .addAction("确定", new QMUIDialogAction.ActionListener() {
                                    @Override
                                    public void onClick(QMUIDialog dialog, int index) {
                                        shouldRequest.again(true);dialog.dismiss();
                                    }
                        }).show();
                    }
                })
                .callback(new PermissionUtils.FullCallback(){
                    @Override
                    public void onGranted(List<String> permissionsGranted){//申请成功的权限
                        if (permissionsGranted.contains(Manifest.permission.ACCESS_COARSE_LOCATION)) {
                            requestLocation();
                        }
                    }
                    @Override
                    public void onDenied(List<String> permissionsDeniedForever,
                                         List<String> permissionsDenied) {//选择了不再提醒  失败的权限
                        if (!permissionsDeniedForever.isEmpty()){
                            PermissionUtils.openAppSettings();
                        }
                    }
                }).request();
    }


    private class MainAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener {

        private List<Fragment> fragments = new ArrayList<>();

        public MainAdapter(FragmentManager fm) {
            super(fm);
            fragments.add(new NotesFragment());
            fragments.add(new StrokeFragment());
            fragments.add(new EnjoyFragment());
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (0 == position) {
                topbar.setTitle(getResources().getString(R.string.notes));
            } else if (1 == position) {
                topbar.setTitle(getResources().getString(R.string.stroke));
            } else if (2 == position) {
                topbar.setTitle(getResources().getString(R.string.enjoy));
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }


    //获取天气数据
    private void getWeatherData(String location){
        //参数字符串，如果拼接在请求链接之后，需要对中文进行 URLEncode   字符集 UTF-8
        String param = "key=31fe89e34b6b4102ae9fab81afc7c36d&location="+location;
        StringBuilder sb = new StringBuilder();
        InputStream is=null;
        BufferedReader br=null;
        PrintWriter out = null;
        try {
            //接口地址
            String url = "https://free-api.heweather.com/s6/weather";
            URL uri = new URL(url);
            HttpURLConnection connection= (HttpURLConnection) uri.openConnection();
            connection.setRequestMethod("POST");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(10000);
            connection.setRequestProperty("accept", "*/*");
            //发送参数
            connection.setDoOutput(true);
            out = new PrintWriter(connection.getOutputStream());
            out.print(param);
            out.flush();
            //接收结果
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line;
            //缓冲逐行读取
            while ( (line = br.readLine()) != null ) {
                sb.append(line);
            }
            UserUtil.dLog("---"+sb.toString());
            if (!sb.toString().isEmpty()) {
                spData(sb.toString());
            }
        }catch ( Exception ignored ){}
        finally {
            //关闭流
            try {
                if(is!=null){
                    is.close();
                }
                if(br!=null){
                    br.close();
                }
                if (out!=null){
                    out.close();
                }
            } catch (IOException e2) {}
        }
    }
    //适配数据
    private void spData(String data){
        WeatherModel weatherModel = GsonImpl.get().toObject(data, WeatherModel.class);
        List<WeatherModel.HeWeather6Bean> heWeather6 = weatherModel.getHeWeather6();
        WeatherModel.HeWeather6Bean heWeather6Bean = heWeather6.get(0);
        WeatherModel.HeWeather6Bean.BasicBean basic = heWeather6Bean.getBasic();
        WeatherModel.HeWeather6Bean.NowBean now = heWeather6Bean.getNow();
        String location = basic.getLocation();//当前区域
        String parent_city = basic.getParent_city();//当前城市
        String fl = now.getFl();
        final String tmp = now.getTmp();//温度
        final String cond_txt = now.getCond_txt();//天气情况
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_username.setText(cond_txt);
                tv_level.setText(tmp+" °C");
            }
        });
    }


    //不销毁activity
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
